'use strict';

const fs = require('fs')
	, path = require('path')
	, fetch = require('node-fetch')

, randomString = (randomLen, min, max) => {
	let str = ''
		, range = min
		, arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
			'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
			'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
			'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
			'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
	if (randomLen) range = Math.round(Math.random() * (max-min)) + min
	for(var i=0; i<range; i++) {
		let pos = Math.round(Math.random() * (arr.length - 1))
		str += arr[pos]
	}
	return str
}

, makeEmail = () => {
	let file = path.resolve(__dirname, 'idx.tmp')
		, idx = parseInt(fs.readFileSync(file, 'utf-8'), 10)
	if (isNaN(idx)) idx = 999999999
	fs.writeFileSync(file, `${++idx}`)
	return `wtf${idx}@qq.com`
}

, signup = async (email, password) => {
	let res = await fetch('https://auth.statnews.com/dbconnections/signup', {
		method: 'POST'
		, headers: {
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
			, 'Content-Type': 'application/json'
		}
		, body: `{"client_id":"76JH6we1YelOD30wngrWIyXT91JCsZpp","state":"${randomString(false, 32)}","nonce":"${randomString(false, 8)}-${randomString(false, 6)}-${randomString(false, 7)}._${randomString(false, 4)}_${randomString(false, 2)}","connection":"Username-Password-Authentication","email":"${email}","password":"${password}","user_metadata":{"name":"","com":"","job":"","org":"Academia","joblevel":"","zip":"","display_name":"${email.split('@')[0]}","group_name":""}}`
		, timeout: 20000
	}).then(res => res.json()).catch(err => false)
	if(!res || res.statusCode) return false
	return res
}

, login = async (email, password) => {
	let res = await fetch('https://auth.statnews.com/co/authenticate', {
		method: 'POST'
		, headers: {
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
			, 'Content-Type': 'application/json'
			, 'origin': 'https://www.statnews.com'
		}
		, body: `{"client_id":"76JH6we1YelOD30wngrWIyXT91JCsZpp","username":"${email}","password":"${password}","realm":"Username-Password-Authentication","credential_type":"http://auth0.com/oauth/grant-type/password-realm"}`
		, timeout: 20000
	}).then(res => res.json()).catch(err => false)
	if(!res || !res.login_ticket) return false
	return res
}

, getCsrf = async () => {
	let htmlCode = await fetch('https://bracket-v3.votion.co/b/f717515e-950f-11ec-8f9b-020163947320/voting/bev', {
		method: 'GET'
		, headers: {
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
			, 'origin': 'https://bracket-v3.votion.co'
		}
		, timeout: 60000
	}).then(res => res.text()).catch(err => false)
	let pos = htmlCode.indexOf(`<input type="hidden" name="id" value="59">`)
		, tmp = htmlCode.substring(pos, pos + 300)
		, csrf = tmp.match(/name="_csrf" value="(.*?)"/gi)[0].match(/"(.*?)"/gi)[1]
	return csrf.substring(1, csrf.length - 1)
}

, submit = async (csrf, fingerprint) => {

}

, main = async () => {
	console.log(`正在注册账号请稍后…`)
	let password = 'a123456'
		, regInfo = await signup(makeEmail(), password)
	if (regInfo !== false) {
		console.log(`已成功注册账号：${regInfo.email}，接下来将登录账号，请稍后…`)
		//console.log(regInfo)
		/*
			{ _id: '623dcbdb680114006f43da55',
			email_verified: false,
			email: 'wtf1000000013@qq.com',
			user_metadata:
			{ name: '',
				com: '',
				job: '',
				org: 'Academia',
				joblevel: '',
				zip: '',
				display_name: 'wtf1000000013',
				group_name: '' } }
		 */
		let loginInfo = await login(regInfo.email, password)
		if(loginInfo !== false) {
			console.log(`账号：${regInfo.email}，login_ticket: ${loginInfo.login_ticket} 登陆完毕，接下来将获取 csrf 值，请稍后…`)
			//console.log(loginInfo)
			/*
				{ login_ticket: 'JbiCQfAZKuptN-zUbVgE2GAQUhMzCptf',
					co_verifier: 'gks9zoUVCqhKz8fnqyF18Fgz64Z-nTsE',
					co_id: 'BB6MrfnLGQtm' }
			*/
			let csrfInfo = await getCsrf()
			if (!csrfInfo) {
				console.error('获取 CSRF 值失败，可能为网络超时，将自动重新尝试！')
			} else {
				console.log(`已成功获取 CSRF 值：${csrfInfo}，将进行投票操作，请稍后…`)
				//await submit
			}
		} else {
			console.error('登录失败，可能为网络超时，将自动重新尝试！')
		}
	} else {
		console.error('注册失败，可能为网络超时，将自动重新尝试！')
	}
}

main()

